# -*- coding: utf-8 -*-
# @author: edgardeng
# @date:   2021-05-08
# @file:  socketserver 实现多并发 服务端

import socketserver


class MyServer(socketserver.BaseRequestHandler):
    def handle(self):
        # 创建一个链接,继承于socketserver中的BaseRequestHandler类
        conn = self.request
        # 发送登录提示
        conn.sendall(b"[Server] Welcome to login...")
        print("[Server] Client connect...")
        while True:
            print("[Server]Waitting for recving message...")
            message = conn.recv(1024)
            if not message:
                message = b'no data'
            data = message.decode('utf-8')
            # 收到exit就退出
            if data == "exit":
                print('close')
                break
            # 发送消息
            reply = f'[Server] replay: got {data}'.encode('utf-8')
            conn.sendall(reply)


if __name__ == "__main__":
    # 实例化
    server = socketserver.ThreadingTCPServer(('127.0.0.1', 999,), MyServer)
    # 调用serve_forever方法
    server.serve_forever()

'''
def serve_forever(self, poll_interval=0.5):
    """
    Handle one request at a time until shutdown.
    Polls for shutdown every poll_interval seconds. Ignores
    self.timeout. If you need to do periodic tasks, do them in
    another thread.
'''
